package com.wyl.studyredis.framework.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

/**
 * 缓存Redis配置
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

	@Autowired
	private RedisConnectionFactory factory;

	/**
	 *  设置@cacheable 序列化方式
	 */
	@Bean
	public RedisCacheConfiguration redisCacheConfiguration(){
		//fastJson默认也有提供一个redis序列化器，但是在fastjson在1.2.25之后的版本后，反序列化的时候会抛出JSONException: autoType is not support
		//FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);

		MyFastJsonRedisSerializer<Object> serializer = new MyFastJsonRedisSerializer<>(Object.class);
		RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
		configuration = configuration
				.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer))
				.entryTtl(Duration.ofDays(30)); // 设置 redis 数据默认过期时间
		return configuration;
	}
}
